package com.party.admin.biz.crowdfund;


import com.party.admin.biz.copartner.MemberCopartnerDetailBizService;
import com.party.admin.biz.distribution.DistributionBizService;
import com.party.common.constant.Constant;
import com.party.common.utils.BigDecimalUtils;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.activity.Activity;
import com.party.core.model.counterfoil.Counterfoil;
import com.party.core.model.counterfoil.CounterfoilBusiness;
import com.party.core.model.crowdfund.*;
import com.party.core.model.distributor.DistributorCount;
import com.party.core.model.distributor.DistributorRelation;
import com.party.core.model.distributor.DistributorRelationType;
import com.party.core.model.member.MemberAct;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.counterfoil.ICounterfoilBusinessService;
import com.party.core.service.counterfoil.ICounterfoilService;
import com.party.core.service.crowdfund.*;
import com.party.core.service.distributor.IDistributorCountService;
import com.party.core.service.distributor.IDistributorDetailService;
import com.party.core.service.member.IMemberActService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 联合发起业务接口
 * Created by wei.li
 *
 * @date 2017/3/2 0002
 * @time 14:12
 */
@Service("ProjectTransferBizService")
@Transactional
public class ProjectTransferBizService {

    @Autowired
    private IProjectService projectService;

    @Autowired
    private IProjectTransferService projectTransferService;

    @Autowired
    private ProjectBizService projectBizService;

    @Autowired
    private IActivityService activityService;

    @Autowired
    private ISupportTransferService supportTransferService;

    @Autowired
    private ISupportService supportService;

    @Autowired
    private IMemberActService memberActService;

    @Autowired
    private ISupportTransferDetailService supportTransferDetailService;

    @Autowired
    private IDistributorCountService distributorCountService;

    @Autowired
    private DistributionBizService distributionBizService;

    @Autowired
    private IDistributorDetailService distributorDetailService;

    @Autowired
    private MemberCopartnerDetailBizService memberCopartnerDetailBizService;

    @Autowired
    private ICounterfoilService counterfoilService;
    @Autowired
    private ICounterfoilBusinessService counterfoilBusinessService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 转换支持
     *
     * @param sourceId 资源编号
     * @param targetId 目标编号
     */

    public void transferSupport(String sourceId, String targetId) {

        Activity activity = activityService.get(targetId);
        Project source = projectService.get(sourceId);

        //根据目标和发起人查询
        Project target = projectService.findByTargetWithAuthor(targetId, source.getAuthorId());

        //已经报名
        if (null != target) {
            if (Constant.IS_CROWFUND_ING.equals(target.getIsSuccess())) {
                //验证众筹金额
                float realAmount = BigDecimalUtils.add(target.getActualAmount(), source.getActualAmount());
                realAmount = BigDecimalUtils.round(realAmount, 2);
                if (realAmount > target.getTargetAmount()) {
                    throw new BusinessException("转移后的金额大于目标金额,不能转移");
                }
                projectTransferService.transfer(sourceId, target.getId());
            } else {
                throw new BusinessException("该用户在该项目已经报名,且状态不对，请核对众筹状态");
            }
        }

        //未报名
        else {
            // 自动报名
            String projectId = projectBizService.apply(activity, source, null);
            projectTransferService.transfer(sourceId, projectId);
        }
    }

    /**
     * 批量转换支持
     *
     * @param sourceId 项目编号
     * @param targetId 目标编号
     */

    public void batchTransferSupport(String sourceId, String targetId) {

        //获取到已经报名,众筹状态正确的项目
        List<ProjectBatchTransfer> hbInvolveds = projectService.findByTargetWithSource(targetId, sourceId);
        for (ProjectBatchTransfer pbt : hbInvolveds) {

            Float tag_actualAmount = pbt.getTagActualAmount();
            String souId = pbt.getSouId();
            Float sou_actualAmount = pbt.getSouActualAmount();
            Float tag_TargetAmount = pbt.getTagTargetAmount();

            float realAmount = BigDecimalUtils.add(tag_actualAmount, sou_actualAmount);
            realAmount = BigDecimalUtils.round(realAmount, 2);
            //当前金额+已有金额小于等于目标金额

            if (realAmount <= tag_TargetAmount) {
                SupportTransfer supportTransfer = new SupportTransfer();
                supportTransfer.setTargetId(targetId);
                supportTransfer.setSourceId(souId);
                String id = supportTransferService.insert(supportTransfer);

                if (StringUtils.isNotBlank(id)) {
                    Project pro = projectService.get(souId);
                    pro.setTransferStatus(1);
                    projectService.update(pro);
                }
            }
        }

        //获取到没有报名的项目
        List<Project> notInvolveds = projectService.findByTargetWithSourceNotInvolved(targetId, sourceId);
        for (Project p : notInvolveds) {
            SupportTransfer supportTransfer = new SupportTransfer();
            supportTransfer.setTargetId(targetId);
            supportTransfer.setSourceId(p.getId());
            String id = supportTransferService.insert(supportTransfer);

            if (StringUtils.isNotBlank(id)) {
                Project pro = projectService.get(p.getId());
                pro.setTransferStatus(1);
                projectService.update(pro);
            }
        }
    }


    /**
     * 众筹成功审核
     *
     * @param sourceId 项目编号
     * @param targetId 目标编号
     */
    public void transferAudit(String sourceId, String targetId, Integer checkStatus) {
        Activity activity = activityService.get(targetId);
        Project source = projectService.get(sourceId);
        SupportTransfer supportTransfer = supportTransferService.getBySourceId(source.getId());

        String targetProId = "";

        //3:审核通过,4审核拒绝)
        int support_sp_state = 4;

        //4:审核通过,5审核拒绝)
        int project_sp_state = 5;

        //审批通过
        if (0 == checkStatus) {
            //根据目标和发起人查询
            Project target = projectService.findByTargetWithAuthor(targetId, source.getAuthorId());

            String counterfoilId = null;

            List<Counterfoil> counterfoils = counterfoilService.list(new Counterfoil(activity.getEventId(),
                    Constant.BUSINESS_TYPE_CROWDFUND));
            if (counterfoils.size() > 1) {
                // 多个票据，且没有报名。则不能转移，因为不知道自动报名时，报名哪个票据
                if (null == target) {
                    throw new BusinessException("目标项目存在多个票据,不能转移");
                }
                CounterfoilBusiness counterfoilBusiness = counterfoilBusinessService.findByBusinessId(target.getId());
                if (null != counterfoilBusiness) {
                    Counterfoil counterfoil = counterfoilService.get(counterfoilBusiness.getCounterfoilId());
                    if (source.getActualAmount() > counterfoil.getPayment()) {
                        throw new BusinessException("转移后的金额大于目标金额,不能转移");
                    }
                    counterfoilId = counterfoil.getId();
                }
            } else if (counterfoils.size() == 1) {
                if (source.getActualAmount() > counterfoils.get(0).getPayment()) {
                    throw new BusinessException("转移后的金额大于目标金额,不能转移");
                }
                counterfoilId = counterfoils.get(0).getId();
            } else if (counterfoils.size() == 0) {
                throw new BusinessException("该项目不存在票据,不能转移");
            }
            //已经报名
            if (null != target) {
                if (Constant.IS_CROWFUND_ING.equals(target.getIsSuccess())) {
                    //验证众筹金额
                    float realAmount = BigDecimalUtils.add(target.getActualAmount(), source.getActualAmount());
                    realAmount = BigDecimalUtils.round(realAmount, 2);
                    if (realAmount > target.getTargetAmount()) {

                        throw new BusinessException("转移后的金额大于目标金额,不能转移");
                    }
                    targetProId = target.getId();

                    // 如果是众筹分销 删除相关的分销关系。
                    this.dealDeleteDetail(targetProId, target.getAuthorId(), targetId, target.getCreateDate());
                    // projectTransferService.transfer(sourceId, target.getId());

                } else {

                    throw new BusinessException("该用户在该项目已经报名,且状态不对，请核对众筹状态");
                }
            } else {
                // 自动报名
                targetProId = projectBizService.apply(activity, source, counterfoilId);
                //projectTransferService.transfer(sourceId, targetProId);
            }

            //转移过来的默认给它众筹时长1分钟，设置最后支持时间LastSupportDate
            Project project = projectService.get(targetProId);
            if (project != null) {
                project.setUseTime(Long.valueOf(60000));
                List<SupportWithMember> byProjectId = supportService.findByProjectId(sourceId);
                SupportWithMember supportWithMember = byProjectId.get(0);
                if (supportWithMember != null) {
                    //最后支持时间
                    project.setLastSupportDate(supportWithMember.getCreateDate());
                }
                projectService.update(project);
                logger.info("projectdid:" + project.getId() + "setUseTime:" + project.getUseTime());
            }


            //记录转移的支持者
            try {
                projectTransferService.recordTransferSupporters(sourceId, supportTransfer.getId());
            } catch (Exception e) {
                logger.error("记录转移的支持者异常", e);
            }

            projectTransferService.transfer(sourceId, targetProId);


            //众筹转移活动报名表状态维护
            try {
                projectTransferService.projectMemberActStateUpdate(targetProId, targetId, counterfoilId);
            } catch (Exception e) {
                logger.error("众筹转移活动报名表状态维护异常", e);
            }


            List<SupportWithMember> tranAfterList = supportService.findByProjectId(sourceId);
            if (tranAfterList.size() == 0) {
                support_sp_state = 3;
                project_sp_state = 4;
            } else {
                throw new BusinessException("转移异常");
            }

            Project targetproject = projectService.get(targetProId);
            if (Constant.IS_SUCCESS.equals(targetproject.getIsSuccess())) {
                try {
                    DistributorRelation targetRelation = distributionBizService.getDistributorRelation(targetProId);
                    if (null != targetRelation) {
                        DistributorCount distributorCount = distributorCountService.findByRelationId(targetRelation.getId());
                        distributorCount.setSuccessNum(distributorCount.getSuccessNum() + 1);
                        distributorCountService.update(distributorCount);
                    }
                    DistributorRelation sourceRelation = distributionBizService.getDistributorRelation(sourceId);
                    if (null != sourceRelation) {
                        DistributorCount distributorCount = distributorCountService.findByRelationId(sourceRelation.getId());
                        distributorCount.setSuccessNum(distributorCount.getSuccessNum() - 1);
                        distributorCountService.update(distributorCount);

                        if (DistributorRelationType.CROWDFUND_DISTRIBUTION.getCode().equals(sourceRelation.getType())) {
                            memberCopartnerDetailBizService.updateSuccessSub(sourceId, source.getCreateDate());
                        }
                    }
                } catch (Exception e) {
                    logger.error("更新联合发起统计异常", e);
                }
            }
        }

        //转移已授权
        supportTransfer = supportTransferService.getBySourceId(source.getId());
        supportTransfer.setIsAuthorized(support_sp_state);
        supportTransfer.setTargetProId(targetProId);
        supportTransferService.update(supportTransfer);

        //众筹项目转移成功
        Project project = projectService.get(sourceId);
        project.setTransferStatus(project_sp_state);
        projectService.update(project);
    }

    /**
     * 如果是众筹分销的分销关系删除
     *
     * @param targetProId 目标众筹id
     * @param authorId    众筹者id
     * @param activityId  活动id
     */
    public void dealDeleteDetail(String targetProId, String authorId, String activityId, Date createDate) {
        DistributorRelation distributorRelation = distributionBizService.getDistributorRelation(targetProId);
        if (null != distributorRelation &&
                DistributorRelationType.CROWDFUND_DISTRIBUTION.getCode().equals(distributorRelation.getType())) {
            MemberAct memberAct = memberActService.findByMemberAct(authorId, activityId);
            if (null != memberAct) {
                distributorDetailService.deleteByTargetId(memberAct.getId(), distributorRelation.getId());
                if (StringUtils.isNotEmpty(memberAct.getOrderId())) {
                    distributorDetailService.deleteByTargetId(memberAct.getOrderId(), distributorRelation.getId());
                }
            }

            distributorDetailService.deleteByTargetId(targetProId, distributorRelation.getId());

            DistributorCount distributorCount = distributorCountService.findByRelationId(distributorRelation.getId());
            distributorCount.setApplyNum(distributorCount.getApplyNum() - 1);
            distributorCount.setCrowdfundNum(distributorCount.getCrowdfundNum() - 1);
            distributorCount.setSalesNum(distributorCount.getSalesNum() - 1);
            distributorCountService.update(distributorCount);


            memberCopartnerDetailBizService.updateApplyNumSub(distributorRelation, createDate);
        }
    }

    public void supporterTransferDataRepair() {
        List<SupportTransferMaintenance> stfmlist = supportTransferService.getSupporterTransfer(0);
        for (SupportTransferMaintenance stfm : stfmlist) {
            logger.error("维护转移的支持者", stfm);
            supportTransferDetailService.insert(new SupportTransferDetail(stfm.getTransferId(), stfm.getSupportId()));
        }


        List<SupportTransferMaintenance> stfmlist1 = supportTransferService.getSupporterTransfer(1);
        for (SupportTransferMaintenance stfm : stfmlist1) {

            logger.error("维护转移的支持者-------转移表", stfm);
            SupportTransfer stobj = supportTransferService.get(stfm.getTransferId());
            stobj.setTargetProId(stfm.getProjectId());
            supportTransferService.update(stobj);
        }
    }
}
